<template>
  <div
    class="md-editor-area"
    :class="{ 'md-editor-area--dark': isDarkTheme }"
    :style="{ height }"
  >
    <div class="md-editor-area__line-numbers" ref="lineNumbersRef">
      <div
        v-for="i in lineCount"
        :key="i"
        class="md-editor-area__line-number"
      >
        {{ i }}
      </div>
    </div>
    <textarea
      ref="textareaRef"
      class="md-editor-area__textarea"
      :value="modelValue"
      :placeholder="placeholder"
      @input="handleInput"
      @keydown="handleKeydown"
      @scroll="handleScroll"
      @select="handleSelect"
      @focus="$emit('focus', $event)"
      @blur="$emit('blur', $event)"
    ></textarea>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useTheme } from '../../hooks/useTheme';

interface Props {
  modelValue: string;
  placeholder?: string;
  height?: string;
  tabSize?: number;
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请输入 Markdown 内容...',
  height: '300px',
  tabSize: 2
});

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
  (e: 'scroll', event: Event): void;
  (e: 'focus', event: FocusEvent): void;
  (e: 'blur', event: FocusEvent): void;
  (e: 'select', text: string, start: number, end: number): void;
}>();

const { currentTheme } = useTheme();
const isDarkTheme = computed(() => currentTheme.value === 'dark');

const textareaRef = ref<HTMLTextAreaElement | null>(null);
const lineNumbersRef = ref<HTMLDivElement | null>(null);

// 计算行数
const lineCount = computed(() => {
  const content = props.modelValue || '';
  return content.split('\n').length;
});

// 处理输入
const handleInput = (event: Event) => {
  const target = event.target as HTMLTextAreaElement;
  emit('update:modelValue', target.value);
};

// 处理按键
const handleKeydown = (event: KeyboardEvent) => {
  // Tab 键处理
  if (event.key === 'Tab') {
    event.preventDefault();
    
    const textarea = textareaRef.value;
    if (!textarea) return;
    
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const value = textarea.value;
    
    // 插入制表符（空格）
    const spaces = ' '.repeat(props.tabSize);
    const newValue = value.substring(0, start) + spaces + value.substring(end);
    
    // 更新值
    emit('update:modelValue', newValue);
    
    // 设置光标位置
    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = start + props.tabSize;
    });
  }
};

// 处理滚动同步
const handleScroll = (event: Event) => {
  const textarea = event.target as HTMLTextAreaElement;
  const lineNumbers = lineNumbersRef.value;
  
  if (lineNumbers) {
    lineNumbers.scrollTop = textarea.scrollTop;
  }
  
  emit('scroll', event);
};

// 处理文本选择
const handleSelect = () => {
  const textarea = textareaRef.value;
  if (!textarea) return;
  
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const selectedText = textarea.value.substring(start, end);
  
  emit('select', selectedText, start, end);
};

// 公开方法
const focus = () => {
  textareaRef.value?.focus();
};

const insertText = (text: string, position?: { start?: number; end?: number }) => {
  const textarea = textareaRef.value;
  if (!textarea) return;
  
  const start = position?.start ?? textarea.selectionStart;
  const end = position?.end ?? textarea.selectionEnd;
  const value = textarea.value;
  
  const newValue = value.substring(0, start) + text + value.substring(end);
  emit('update:modelValue', newValue);
  
  nextTick(() => {
    textarea.selectionStart = textarea.selectionEnd = start + text.length;
    textarea.focus();
  });
};

const getSelectedText = () => {
  const textarea = textareaRef.value;
  if (!textarea) return '';
  
  return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
};

const setSelectedText = (text: string) => {
  const textarea = textareaRef.value;
  if (!textarea) return;
  
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const value = textarea.value;
  
  const newValue = value.substring(0, start) + text + value.substring(end);
  emit('update:modelValue', newValue);
  
  nextTick(() => {
    textarea.selectionStart = start;
    textarea.selectionEnd = start + text.length;
    textarea.focus();
  });
};

// 同步滚动条
watch(() => props.modelValue, () => {
  nextTick(() => {
    const textarea = textareaRef.value;
    const lineNumbers = lineNumbersRef.value;
    
    if (textarea && lineNumbers) {
      lineNumbers.scrollTop = textarea.scrollTop;
    }
  });
});

// 暴露方法
defineExpose({
  focus,
  insertText,
  getSelectedText,
  setSelectedText
});
</script>

<style lang="scss" scoped>
.md-editor-area {
  display: flex;
  border: 1px solid var(--md-borderColor, #e0e0e0);
  border-top: none;
  background-color: var(--md-backgroundColor, #ffffff);
  color: var(--md-textColor, #333333);
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  line-height: 1.6;
  overflow: hidden;
  
  &--dark {
    background-color: var(--md-backgroundColor, #1e1e1e);
    color: var(--md-textColor, #e0e0e0);
  }
  
  &__line-numbers {
    flex-shrink: 0;
    width: 40px;
    padding: 10px 0;
    background-color: rgba(0, 0, 0, 0.03);
    border-right: 1px solid var(--md-borderColor, #e0e0e0);
    text-align: center;
    color: #999;
    font-size: 12px;
    overflow: hidden;
    user-select: none;
  }
  
  &__line-number {
    height: 1.6em;
  }
  
  &__textarea {
    flex: 1;
    padding: 10px;
    border: none;
    resize: none;
    background-color: transparent;
    color: inherit;
    font-family: inherit;
    font-size: 14px;
    line-height: 1.6;
    outline: none;
    overflow-y: auto;
    
    &::placeholder {
      color: #999;
    }
  }
}
</style>